# -*- coding=utf-8

# werobot
# README
# 可用 Alist 或其他可挂载 S3 的开源网盘 实现web编辑.md

import werobot
from obcs import timeFmt
import wechat_article

from config import obcos
# 相关信息
import configparser

config = configparser.ConfigParser()
config.read('config.ini', encoding="utf-8")
sections = config.sections()

token = config.get('WeChat','Token')  # 自定义
APP_ID = config.get('WeChat','appID')  # 微信公众号测试号APP_ID
APP_SECRET = config.get('WeChat','appsecret')  # 微信公众号测试号APP_SECRET
openid = config.get('WeChat','OpenId')


# werobot 配置

robot = werobot.WeRoBot(token=token)
robot.config["APP_ID"] = APP_ID
robot.config["APP_SECRET"] = APP_SECRET

rob_client = robot.client
# rob_client.delete_menu()

# 
# rob_client.create_menu({
#     "button":[{
#          "type": "click",
#          "name": "今日",
#          "key": "info"
#     }]
# })

messagelist = []
readUrl = "<a href='"+ config.get('global','web_url') + ">点击查看今日笔记</a>"
reply_str  = "📩 已保存，"+ readUrl 

@robot.key_click("info")
def menu_click(message):
    if (message.source != openid):
        return '你不是恐咖兵糖'
    return obcos.today_daily()

# 关注回复
@robot.subscribe
def subscribe(message):
    return "这是恐咖兵糖的测试公众号"


# 文字消息回复 put_object append_object
@robot.text
def text_reply(message):
    if (message.message_id in messagelist):
        return '排重'
    # if (len(messagelist) >= 100 ):
    #     messagelist.clear()
    messagelist.append(message.message_id)
    if (message.source != openid):
        return '你不是恐咖兵糖'
    daily_str = ''
    # 监测到以 h
    if(message.content.startswith('http://') or message.content.startswith('https://') ):
        daily_str = wx_save2ob(message.content)
    r_str = obcos.append_memos_in_daily(message.content + ' <br>' +daily_str)
    return reply_str + str(len(messagelist))


# 图片消息
@robot.image
def image_reply(message):
    if (message.message_id in messagelist):
        return '排重'
    messagelist.append(message.message_id)
    if (message.source != openid):
        return '你不是恐咖兵糖'
    file_key = obcos.daily_attachment_file_dir() + timeFmt("%Y%m%d%H%M%S") + ".jpg"
    now_key = obcos.store_by_url(file_key,message.img)
    r_str = obcos.append_memos_in_daily('!['+message.img+']('+file_key+')')
    return  reply_str + str(len(messagelist))

# 链接消息
@robot.link
def link_reply(message):
    if (message.message_id in messagelist):
        return '排重'
    messagelist.append(message.message_id)
    if (message.source != openid):
        return '你不是恐咖兵糖'
    daily_str = wx_save2ob(message.url) # 保存文章
    link_str =  "[" +message.title +"](" + message.url + ")<br>" + message.description + '... ' + str(daily_str)
    r_str = obcos.append_memos_in_daily(link_str)
    return reply_str + str(len(messagelist))

# 位置消息
@robot.location
def location_reply(message):
    if (message.message_id in messagelist):
        return '排重'
    messagelist.append(message.message_id)
    if (message.source != openid):
        return '你不是恐咖兵糖'
    location_str =  "经纬: " +  str(message.location) + " 地理位置: " + message.label
    r_str = obcos.append_memos_in_daily(location_str)
    return reply_str + str(len(messagelist))

# 语音消息
@robot.voice
def voice_reply(message):
    if (message.message_id in messagelist):
        return '排重'
    messagelist.append(message.message_id)
    if (message.source != openid):
        return '你不是恐咖兵糖'
    voice_str =  "语音: " + message.recognition
    r_str = obcos.append_memos_in_daily(voice_str)
    return reply_str + str(len(messagelist))

# 视频消息
@robot.video
def video_reply(message):
    if (message.message_id in messagelist):
        return '排重'
    messagelist.append(message.message_id)
    if (message.source != openid):
        return '你不是恐咖兵糖'
    return "不支持的消息类型"

@robot.error_page
def make_error_page(url):
    return "404"


@robot.handler
def error_message(message):
    return "不支持的消息类型"


def wx_save2ob(url):
    daily_str = ''
    try:
        text = wechat_article.get_weixin_md(url)
        file_key = "支持类文件/微信文章/" + timeFmt("%Y%m%d%H%M%S") + ".md"
        mdtext = "---\ntitle: {}\nwxtime: {}\n---\n# {}\n{}\n{}".format(text['title'],text['time'],text['title'],text['time'],text['md'])
        obcos.store(file_key, bytes(mdtext,encoding='utf-8'))
        daily_str = "文章详情 [{}]({}).".format(text['title'], file_key)
    except Exception as e:
        print(e)
        daily_str = "抓取失败"
    return daily_str

# robot.config["HOST"] = "0.0.0.0"
# robot.config["PORT"] = "8008"
# robot.run()
